<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            current-node-key=""
            highlight-current
            @node-click="handleNodeClick"
            empty-text="数据加载中"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="queryParams.productName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select
              v-model="queryParams.goodsBrandId"
              filterable
              placeholder="请选择品牌"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.brandName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['commodity:product:add']"
              >新增</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['commodity:product:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain size="mini" @click="handleExport"
              >导出</el-button
            >
          </el-col>

          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          v-loading="loading"
          :data="productList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="品牌" align="center" prop="goodsBrand">
            <template slot-scope="scope">
              <el-tag>{{ scope.row.goodsBrand }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="商品名称" align="center" prop="productName" />

          <el-table-column label="商品售价" align="center" prop="shopPrice" />
          <el-table-column label="商品原价" align="center" prop="marketPrice" />
          <el-table-column label="商品主图">
            <template slot-scope="scope">
              <el-image
                :src="scope.row.previewImg"
                fit="fill"
                :preview-src-list="[scope.row.previewImg]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="是否上架" align="center" prop="isShow">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="是否热卖" align="center" prop="isHotSale">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isHotSale"
                :active-value="1"
                :inactive-value="0"
                @change="handleHot(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="是否推荐" align="center" prop="isRecommend">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isRecommend"
                :active-value="1"
                :inactive-value="0"
                @change="handleRecommend(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="排序" align="center" prop="sort">
            <template slot-scope="scope">
              {{ scope.row.sort }}
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleSort(scope.row)"
                v-hasPermi="['commodity:product:updateLocalSort']"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="本地设置库存数"
            align="center"
            prop="localStockNum"
          >
            <template slot-scope="scope">
              {{ scope.row.localStockNum }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['commodity:product:edit']"
                >修改</el-button
              >
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
                v-hasPermi="['commodity:product:detail']"
                >查看详情</el-button
              > -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['commodity:product:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAddSpec(scope.row)"
                v-hasPermi="['commodity:product:addSpec']"
                >添加规格</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改商城商品对话框 -->
    <el-dialog
      :title="title"
      style="padding: 10px"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <div style="height: 700px; overflow-y: auto">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="0" style="box-sizing: border-box">
            <el-col :span="12">
              <el-form-item label="商品分类" prop="cateId">
                <treeselect
                  v-model="form.cateId"
                  :options="adddeptOptions"
                  :normalizer="normalizer"
                  placeholder="选择商品分类"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="productName">
                <el-input
                  v-model="form.productName"
                  placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item label="商品简介" prop="productBriefIntroduction">
                <el-input
                  v-model="form.productBriefIntroduction"
                  placeholder="请输入商品简介"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item label="商品品牌" prop="goodsBrandId">
                <el-select
                  v-model="form.goodsBrandId"
                  placeholder="请选择商品品牌"
                >
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.brandName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="市场价格" prop="marketPrice">
                <el-input
                  v-model="form.marketPrice"
                  placeholder="请输入市场价格"
                  maxlength="30"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item label="成本价格" prop="costPrice">
                <el-input
                  v-model="form.costPrice"
                  placeholder="请输入成本价格"
                  maxlength="30"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商城售价" prop="shopPrice">
                <el-input
                  v-model="form.shopPrice"
                  placeholder="请输入商城售价"
                  maxlength="30"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item label="是否上架" prop="isShow">
                <el-radio-group v-model="form.isShow">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属应用场景" prop="productTag">
                <el-select
                  v-model="form.productTag"
                  multiple
                  placeholder="请选择应用场景"
                >
                  <el-option
                    v-for="item in productTagList"
                    :key="item.goodsTagId"
                    :label="item.goodsTag"
                    :value="item.goodsTagId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item label="本地库存数" prop="localStockNum">
                <el-input
                  type="number"
                  v-model="form.localStockNum"
                  placeholder="请输入本地库存数"
                  min="0"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="商品主图" prop="previewImg">
                <Image-Upload
                  :value="form.previewImg"
                  :limit="1"
                  @input="getImgUrlEdit"
                ></Image-Upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品轮播图" prop="imgList">
                <Image-Upload
                  :value="form.imgList"
                  :multiple="true"
                  :limit="5"
                  @input="getImgList"
                ></Image-Upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会员价">
                <el-input
                  v-model="form.memberPrice"
                  placeholder="请输入会员价"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否参与折扣">
                <el-radio-group v-model="form.isMember">
                  <el-radio :label="0">不参与</el-radio>
                  <el-radio :label="1">参与</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item label="服务标题">
                <el-input
                  v-model="form.goodsServiceTitle"
                  placeholder="请输入服务标题"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="服务内容" prop="goodsServiceContent">
                <Editor v-model="form.goodsServiceContent" :minHeight="200" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="商品详情" prop="details">
                <Editor v-model="form.details" :minHeight="200" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="subLoading" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排序 -->
    <el-dialog title="修改排序" :visible.sync="isSort" width="400px">
      <el-form
        :model="sortForm"
        ref="sort"
        :rules="sortRule"
        label-width="80px"
      >
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="sortForm.sort"
            placeholder="请输入商品排序"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSort">确 定</el-button>
        <el-button @click="isSort = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPriList,
  addPriGoods,
  editPri,
  delProduct,
  getInfoPri,
  bargainList,
  category,
  updateIsShow,
  updateIsHotSale,
  updateIsRecommend,
  changeLocalStockNum,
  showBankPriceList,
  changeSort,
} from "@/api/company/localProduct";
import { brandList, tagListAllPri } from "@/api/company/brand";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Product",
  components: { Treeselect },
  data() {
    const numValidate = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error("自定义价格不得小于0元"));
      } else {
        return callback();
      }
    };
    return {
      //同步按钮加载
      syncLoad: false,
      isNum: false,
      numForm: {},
      numRule: {},
      isSort: false,
      sortForm: {
        sort: null,
      },
      sortRule: {
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      subLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城商品表格数据
      productList: [],
      productTagList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      adddeptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "name",
      },
      categoryName: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        cateId: null,
      },
      //议价列表
      bargainList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cateId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goodsBrandId: [
          { required: true, message: "请选择商品品牌", trigger: "blur" },
        ],
        marketPrice: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        localStockNum: [
          { required: true, message: "请输入本地库存", trigger: "blur" },
        ],
        shopPrice: [
          { required: true, message: "请输入商城售价", trigger: "blur" },
        ],
        // previewImg: [
        //   { required: true, message: "请选择商品主图", trigger: "blur" }
        // ],
        // imgList: [
        //   { required: true, message: "请选择商品轮播图", trigger: "blur" }
        // ],

        details: [
          { required: true, message: "请输入商品详情", trigger: "blur" },
        ],
        isShow: [
          { required: true, message: "请选择是否上架", trigger: "blur" },
        ],
      },
      brandList: [],
      //返现列表
      showBankPriceList: [],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getBrandList();
    // this.getCashbackList();
    //重新请求后台，返回新的菜单列表
    // if (this.$route.query.backUserId) {
    //   this.$store
    //     .dispatch("GenerateRoutes", { userId: this.$route.query.backUserId })
    //     .then((accessRoutes) => {
    //       this.$router.addRouters(accessRoutes);
    //     });
    // }
    const mallId = this.$route.query.id;
    if (mallId) {
      this.$store.dispatch("childMallLogin", { mallId }).then(() => {
        this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
          this.$router.addRouters(accessRoutes);
        });
      });
    }
  },
  watch: {
    // 根据名称筛选部门树
    categoryName(val) {
      console.log(val);
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 添加规格
    handleAddSpec(row) {
      const { id } = row;
      this.$router.push({
        path: "addSpec",
        query: {
          id,
        },
      });
    },
    getCashbackList() {
      showBankPriceList().then((res) => {
        this.cashbackList = res.data;
      });
    },
    /** 查询品牌列表 */
    getBrandList() {
      brandList().then((res) => {
        console.log(res);
        this.brandList = res.rows;
      });
    },
    /** 查询应用场景列表接口 */
    getTagListAllPri() {
      tagListAllPri().then((res) => {
        console.log(res);
        this.productTagList = res.data;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      console.log(node);
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    //是否推荐
    handleRecommend(row) {
      const { mallProductId, isRecommend } = row;

      let text = row.isRecommend == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "推荐吗？")
        .then(function () {
          return updateIsShow({ mallProductId, isRecommend });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isRecommend = row.isRecommend == 1 ? 0 : 1;
        });
    },
    getImgUrlEdit(e) {
      this.form.previewImg = e;
    },
    getImgList(e) {
      console.log(e);
      this.form.imgList = e;
    },
    //是否返现
    handleCashBank(row) {
      const { productId: mallProductId, isCashBank } = row;

      let text = row.isCashBank == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "返现吗？")
        .then(function () {
          return updateIsRecommend({ mallProductId, isCashBank });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isCashBank = row.isCashBank == 1 ? 0 : 1;
        });
    },
    //是否热卖
    handleHot(row) {
      const { mallProductId, isHotSale } = row;

      let text = row.isHotSale == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "热卖吗？")
        .then(function () {
          return updateIsShow({ mallProductId, isHotSale });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isHotSale = row.isHotSale == 1 ? 0 : 1;
        });
    },
    //修改库存
    handleNum(row) {
      this.isNum = true;
      this.numForm = {
        localStockNum: row.localStockNum,
        mallProductId: row.productId,
      };
    },
    // 修改排序
    handleSort(row) {
      this.isSort = true;
      const { mallProductId, sort } = row;
      this.sortForm = {
        mallProductId,
        sort,
      };
    },
    //提交商品库存
    submitFormNum() {
      this.$refs["num"].validate((valid) => {
        if (valid) {
          changeLocalStockNum(this.numForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isNum = false;
            this.getList();
          });
        }
      });
    },
    // 提交排序
    submitFormSort() {
      this.$refs["sort"].validate((valid) => {
        if (valid) {
          changeSort(this.sortForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isSort = false;
            this.getList();
          });
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      category().then((response) => {
        const all = { id: 0, name: "全部" };
        let newData = this.handleTree(response.data, "productCategoryId");
        newData.unshift(all);
        this.deptOptions = newData;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(data);
      this.queryParams.cateId = data.id;
      // this.queryParams.level = data.level;
      this.queryParams.level = 1;

      this.handleQuery();
    },
    //是否上架
    handleStatusChange(row) {
      console.log(row);
      const { mallProductId, isShow } = row;

      let text = row.isShow == 1 ? "上架" : "下架";
      this.$modal
        .confirm("确认要" + text + "吗？")
        .then(function () {
          return updateIsShow({ mallProductId, isShow });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShow = row.isShow == 1 ? 0 : 1;
        });
    },
    /** 查询商城商品列表 */
    getList() {
      this.loading = true;
      const data = {
        ...this.queryParams,
        mallId: this.$route.query.id,
      };
      console.log(data);
      getPriList(data).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productTag: [],
        isMember: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 跳转详情
    handleDetail(row) {
      const id = row.productId;
      this.$router.push({
        path: "/mallGuan/goodsDetail",
        query: {
          id,
        },
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.getTagListAllPri();
      // this.open = true;
      // this.title = "添加商城商品";
      // showAllCategoryPriList().then((response) => {
      //   this.adddeptOptions = this.handleTree(response.data, "id");
      // });
      this.$router.push({
        path: "goodsAbout",
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.$router.push({
        path: "goodsAbout",
        query: {
          id: row.id,
        },
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.productTag.length >= 1) {
            this.form.productTag = this.form.productTag.toString();
          }
          if (this.form.id != undefined) {
            editPri(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPriGoods(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mallProductId = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delProduct(mallProductId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "commodity/localProduct/exportProduct",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
